package com.hsy.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsy.pojo.User;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/userSystem/register")
public class RegisterServlet extends HttpServlet {
    public UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8"); // 防止post请求乱码，设置请求的参数字符集为UTf-8
        resp.setContentType("application/json;charset=UTF-8");  // // 设置响应头，指定返回数据的格式为JSON以及字符编码
        // 使用jackson的ObjectMapper将前端传来的JSON数据转化为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 通过readValue，将前端传来的JSON数据转化成User对象
        User user = objectMapper.readValue(req.getInputStream(), User.class);
        // 转化之前，一定要注意，User对象的属性名要和前端换来的JSON格式数据一致

        boolean registerSuccess = false;
        registerSuccess = userService.checkUserNotExist(user);
        int result = userService.insert(user);      // 注册返回影响数据库行数
        // 根据注册结果构建返回给前端的响应数据
        Map<String, Object> responseData = new HashMap<>();
        if (registerSuccess && result > 0) {
            responseData.put("success", true);
            responseData.put("message", "注册成功");
        } else {
            responseData.put("success", false);
            responseData.put("message", "注册失败,账号或昵称已存在");
        }

        // 将响应数据转换为JSON字符串
        String responseJson = objectMapper.writeValueAsString(responseData);

        // 通过PrintWriter将JSON格式的响应数据写回给前端
        PrintWriter writer = resp.getWriter();
        writer.write(responseJson);
        writer.flush();
        writer.close();
    }
}
